//
//  StatusListViewModel.swift
//  Weibo
//
//  Created by 李亚乐 on 15/12/11.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import Foundation
import SDWebImage

/// 微博数据模型 - 封装网络方法
// MARK: - 微博列表视图模型
class StatusListViewModel {
    
    lazy var statusList = [StatusViewModel]()
    
    func loadData(isPullup: Bool, finished: (isSuccessed: Bool) -> ()) {
        
//        NetworkTools.sharedTools.loadStatus { (success, failure) -> () in
        // 下拉刷新 - 数组中第一条微博的id
        let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
        // 上拉刷新 - 数组中最后一条微博的id
        let max_id = isPullup ? (statusList.last?.status.id ?? 0) : 0

        
        NetworkTools.sharedTools.loadStatus(since_id: since_id, max_id: max_id) { (success, failure) -> () in
            
            if failure != nil {
                print("微博加载出错")
                finished(isSuccessed: false)
                return
            }
            
            guard let dataArray = success?["statuses"] as? [[String: AnyObject]] else {
                print("格式不正确")
                finished(isSuccessed: false)
                return
            }
            
            //可变数组
            var arrayM = [StatusViewModel]()
            //循环遍历数组 创建模型对象
            for dict in dataArray {
                
                arrayM.append(StatusViewModel(status: Status(dict: dict)))
            }
            QL1("刷新到 \(arrayM.count) 条数据")

            // 判断是否是上拉刷新
            if max_id > 0 {
                self.statusList += arrayM
            } else {
            self.statusList = arrayM + self.statusList
            }
            // TODO: 查看数据
//            print(self.statusList)
            
            self.cacheSingleImage(arrayM, finished: finished)
        }

    }
    
    /// 缓存单张图片
    ///
    /// - parameter dataList: 视图模型数组
    /// - parameter finished: 下载完成回调
    private func cacheSingleImage(dataList: [StatusViewModel], finished: (isSuccessed: Bool) -> ()) {
        
        let group = dispatch_group_create()
        
        var datalength = 0
        
        for vm in dataList {
            if vm.thumbnailURLs?.count != 1 {
                continue
            }
 
            let url = vm.thumbnailURLs![0]
//            print("开始缓存图片 \(url)")
            
            dispatch_group_enter(group)
            
            //SDWebImage 核心函数
            //包括本地缓存
            SDWebImageManager.sharedManager().downloadImageWithURL(url,
                options: [],
                progress: nil,
                completed: { (image, _, _, _, _) -> Void in
                    if let img = image, data = UIImagePNGRepresentation(img) {
                        datalength += data.length
                    }
                    
                    dispatch_group_leave(group)
            })
        }
        
        //调度组完成
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            
            print("缓存完成 \(datalength / 1024)")
            finished(isSuccessed: true)
        })
    }
}




